package com.example.filetransfer.publicsource.fileutils;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlReader {

    private final String FILE = "file";
    private final String DIR = "dir";

    private Dir dirRoot = null;

    public Dir getRootDir() {
        return dirRoot;
    }

    public void parserXml(String fileName) {
        File inputXml = new File(fileName);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputXml);
            Element root = document.getRootElement();
            dirRoot = addChildDir(root);
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }
    }

    public Dir addChildDir(Element element){
        String currenPath = element.attributeValue("path");
        Dir currentDir = new Dir(currenPath);
        for (Iterator i = element.elementIterator(); i.hasNext();) {
            Element child = (Element) i.next();
            if(FILE.equals(child.getName())){
                String path = child.attributeValue("path");
                String lastChange = child.attributeValue("lastModify");
                currentDir.addChildFile(new MyFile(new File(path).toString(), lastChange));
            } else if(DIR.equals(child.getName())){
                Dir current = addChildDir(child);
                currentDir.addChildDir(current);
            }
        }
        return currentDir;
    }

    public static void main(String[] args) {
        XmlReader reader = new XmlReader();
        reader.parserXml("D:\\test\\.filetree.xml");
        Dir root = reader.getRootDir();
        XmlSaver saver = new XmlSaver("D:\\test\\test.xml");
        saver.saveDir(root);
    }
}
